const { READ_FETCH_URL } = require('./constants/index');

// 生成接口定义文本
const getUrlText = (url = READ_FETCH_URL) => {
  return `const url = \`\${prefix}/v1/\${organizationId}/${url}\`;`;
}

// 生成接口返回文本
const getReturnText = (method = 'GET') => {
  const returnText = `return {
        ...config,
        url,
        method: '${method}',
      };`;
  return returnText;
}

// 生成请求内容文本
const getFetchText = ({ url = READ_FETCH_URL, method = 'GET', type = 'read' }) => {
  const urlText = getUrlText(url);
  const returnText = getReturnText(method);
  const text = `${type}: (config) => {
      ${urlText}
      ${returnText}
    },`;

  return text;
}

// 生成transport文本
const createTransportText = ({ readUrl = READ_FETCH_URL, submitUrl, destroyUrl }) => {
  // 所有请求文本
  let text = '';

  if(readUrl) {
    // 获取read请求文本
    const readText = getFetchText({ url: readUrl, method: 'GET', type: 'read' });
    text = text + readText;
  }

  if(submitUrl) {
    // 获取submit请求文本
    const submitText = getFetchText({ url: submitUrl, method: 'POST', type: 'submit' });
    text = text + `\n    ${submitText}`;
  }

  if(destroyUrl) {
    // 获取destroy请求文本
    const destroyText = getFetchText({ url: destroyUrl, method: 'DELETE', type: 'destroy' });
    text = text + `\n    ${destroyText}`;
  }
  
  return `transport: {
    ${text}
  },\n`;
}

module.exports = {
  createTransportText,
};